package top.luoyuanxiang.personalknowledgebase.config;

import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.ollama.OllamaChatModel;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.milvus.MilvusVectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * AI聊天配置
 *
 * @author luoyuanxiang
 */
@Configuration
public class ChatConfig {

    @Resource
    private OllamaChatModel ollamaChatModel;
    @Resource
    private RedisChatMemory redisChatMemory;
    @Resource
    private MilvusVectorStore milvusVectorStore;
    @Value("classpath:/prompts/system-qa.st")
    private org.springframework.core.io.Resource systemResource;

    @Bean
    public ChatClient chatClient() throws IOException {
        SearchRequest searchRequest = SearchRequest.builder().topK(7).build();
        String promptTemplate = systemResource.getContentAsString(StandardCharsets.UTF_8);
        return ChatClient.builder(ollamaChatModel)
                .defaultSystem("你是一个RAG知识库问答机器人，致力于解决用户提出的问题，并给出详细的解决方案")
                .defaultAdvisors(new MessageChatMemoryAdvisor(new InMemoryChatMemory()),
                        new QuestionAnswerAdvisor(milvusVectorStore, searchRequest, promptTemplate))
                .build();
    }
}
